<?php

namespace co2_OS;

use co2\dev\v0_0_0 as api;

class aptitude

{
  const
    TYPE_APP  = 1,
    TYPE_LIB  = 2,
    TYPE_API  = 3
    ;

	protected static
	  $db,
		$data,
		$items=array()
		;
		
	public function
	__construct()
	
	{
	  self::$db=new api\PDO('sqlite',sysvar::get('db').'/sqlite3/conf.db');
	}
	
	public static function
	type(
	  $type
	)
	
	{
	  switch((int)$type)
	  
	  {
	    case self::TYPE_APP:  return 'app'; break;
	    case self::TYPE_LIB:  return 'lib'; break;
	    case self::TYPE_API:  return 'api'; break;
	  }
	}

	public static function
	get(
		$type=null,
		$pkg=null,
		$version=null,
		$channel=null
	)
	
	{
	  if(is_null(self::$db))
	  new self;
	  
	  $query="select * from aptitude";
	  
	  $where=array();
	  $params=array();
	  
	  if(!is_null($type))
	  {
	    $where[]="`type` = ?";
	    $params[]=$type;
	  }
	  
	  if(!is_null($pkg))
	  {
	    $where[]="`pkg` = ?";
	    $params[]=$pkg;
	  }
	  
	  if(!is_null($version))
	  {
	    $where[]="`version` = ?";
	    $params[]=$version;
	  }
	  
	   if(!is_null($channel))
	  {
	    $where[]="`channel` = ?";
	    $params[]=$channel;
	  }
	  
	  if(count($where))
	  $query.=" where ".implode(' AND ',$where);
	  
	  $query.=' order by pkg';
	  
		$fetch=self::$db->run($query,$params);

		return $fetch->fetchAll(\PDO::FETCH_CLASS);
	}
	
	public static function
	fetch(
		$id
	)
	
	{
	  if(is_null(self::$db))
	  new self;
	  
	  $query="select * from aptitude where id=?";
	  
		$fetch=self::$db->run($query,array($id));

		return $fetch->fetch(\PDO::FETCH_CLASS|\PDO::FETCH_CLASSTYPE);
	}
	
	public static function
	exists(
		$type,
		$name,
		$version
	)
	
	{
		return preg_match("/$type,$name,$version/",self::$data);
	}
	
	public static function
	add(
		$type,
		$name,
		$version,
		$channel=null
	)
	
	{
	  log::register("APTITUDE_ADD: Received insert signal for type($type) $name version $version channel $channel");
	
	  if(is_null(self::$db))
	  new self;
	  
		self::$db->run("insert into aptitude values(NULL,$type,?,?,?)",array($name,$version,$channel));
		
		log::register("APTITUDE_ADD: Ok :)");
	}
	
	public static function
	delete(
	  $id
	)
	
	{
	  log::register("APTITUDE_DELETE: Received delete signal for package #$id");
	  
	  if(is_null(self::$db))
	  new self;

		self::$db->run("delete from aptitude where id=?",array($id));
		
		log::register("APTITUDE_DELETE: Ok :)");
	}
}
